%%%-------------------------------------------------------------------
%%% @author Rain
%%% @doc 角色进程
%%% @end
%%%-------------------------------------------------------------------
-module(role_svr).

-behaviour(game_server).
-include("common.hrl").
-include("role.hrl").

-export([start_link/0]).
-export([init/1, do_call/3, do_cast/2, do_info/2, terminate/2,
    code_change/3]).
-export([start_role_svr_agent/0]).
-export([get_role/1]).

-export([role_id_to_client_msg/2, role_to_client_msg/1]).

%%%===================================================================
%%% Spawning and gen_server implementation
%%%===================================================================

start_link() ->
    game_server:start_link(?MODULE, [], []).

init([]) ->
    {ok, #role_state{}}.

do_call(_Request, _From, State = #role_state{}) ->
    {noreply, State}.

do_cast(_Request, State = #role_state{}) ->
    {noreply, State}.

%% @doc 激活网关
do_info({active_gate, GatePid}, State = #role_state{}) ->
    set_gate_pid(GatePid),
    {noreply, State};

do_info({gate_msg, Msg}, State = #role_state{}) ->
    MsgName = element(1, Msg),
    #{handler := Handler} = proto_cmd:by_msg_name(MsgName),
    Handler:handle_c2s_msg(Msg, State);

%% @doc 其他进程发送给客户端信息
do_info({o2c_msg, Msg}, State = #role_state{}) ->
    role_to_client_msg(Msg),
    {noreply, State};

do_info(_Info, State = #role_state{}) ->
    {noreply, State}.

terminate(_Reason, _State = #role_state{}) ->
    ok.

code_change(_OldVsn, State = #role_state{}, _Extra) ->
    {ok, State}.

%% @doc 设置网关的pid
set_gate_pid(GatePid) ->
    put(gate_pid, GatePid).

%% @doc 获取网关的pid
get_gate_pid() ->
    get(gate_pid).


%% @doc 启动角色进程代理服务
start_role_svr_agent() ->
    game_util:start_child(role_sup, []).

%% @doc 发送给客户端的消息
role_id_to_client_msg(RoleId, Msg) when is_integer(RoleId) ->
    case role_mgr_svr:get_role_pid(RoleId) of
        Pid when is_pid(Pid) ->
            Pid ! {o2c_msg, Msg};
        _ ->
            pass
    end.

%% @doc 获取角色数据
get_role(RoleId) ->
    Role = get({role, RoleId}),
    Role.


%% @doc 角色进程发送给客户端的消息
role_to_client_msg(Msg) ->
    Pid = get_gate_pid(),
    case is_pid(Pid) of
        ?true ->
            case is_process_alive(Pid) of
                ?true ->
                    Pid ! {r2c_msg, Msg};
                _ ->
                    throw(gate_pid_dead)
            end;
        _ ->
            throw(gate_not_active)
    end.




%%%===================================================================
%%% Internal functions
%%%===================================================================
